package com.anysoft.user.bankcard;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.BaseBean;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.dialog.IcbcDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName：gy_fund-android
 * @ClassDescription： 修改手机号
 * @CreateUser： yanbin
 * @CreateTime：2017-03-10 15:57
 * @ModifiedUser：
 * @ModifiedTime：
 * @ModifiedRemark：
 */

public class EditMobileActivity extends BaseActivity {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.leftButton)
    Button leftButton;

    @BindView(R.id.et_mobile_val)
    EditText et_mobile_val;
    @BindView(R.id.et_verification_code_val)
    EditText et_verification_code_val;
    @BindView(R.id.btn_get_verification_code)
    Button btn_get_verification_code;
    @BindView(R.id.btn_confirm_edit)
    Button btn_confirm_edit;

    private String sMobileNo;
    private TimeCount time;
    /**
     * 是否已获取短信验证码
     */
    private boolean isGetVerificationCode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_mobile);
        ButterKnife.bind(this);
        title.setText("修改手机号");
        time = new TimeCount(1 * 120 * 1000, 1000);
        btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
        btn_get_verification_code.setClickable(false);
        et_mobile_val.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //输入文本之前的状态
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入文字中的状态，count是一次性输入字符数
                if (isTimeOver) {
                    if (Pattern.matches(MentorConst.REGEX_MOBILE, et_mobile_val.getText().toString())) {
                        btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
                        btn_get_verification_code.setClickable(true);
                    } else {
                        btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                        btn_get_verification_code.setClickable(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //输入文字后的状态
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.btn_get_verification_code, R.id.btn_confirm_edit})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            switch (view.getId()) {
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.btn_get_verification_code:
                    if (Pattern.matches(MentorConst.REGEX_MOBILE, et_mobile_val.getText().toString())) {
//                    time.start();
                        sMobileNo = "";
                        sendSmsCode(et_mobile_val.getText().toString());
                    } else {
//                    showToast("手机号格式不对");
                        showConfirmAlert(mActivity, "手机号格式不对");
                    }
                    break;
                case R.id.btn_confirm_edit:
                    save();
                    break;
            }
        }
    }

    private boolean checkData() {
        String mobile = et_mobile_val.getText().toString();
        String verification_code = et_verification_code_val.getText().toString();
        if (StringUtils.isNullOrEmpty(mobile)) {
//            showToast("请输入手机号");
            showConfirmAlert(mActivity, "请输入手机号");
            return false;
        }
        if (!Pattern.matches(MentorConst.REGEX_MOBILE, mobile)) {
//            showToast("手机号格式不对");
            showConfirmAlert(mActivity, "手机号格式不对");
            return false;
        }
        if (!isGetVerificationCode) {
//            showToast("请先获取短信验证码");
            showConfirmAlert(mActivity, "请先获取短信验证码");
            return false;
        }
        if (!mobile.equals(sMobileNo)) {
            showConfirmAlert(mActivity, "您修改了手机号，请重新获取短信验证码");
            return false;
        }
        if (StringUtils.isNullOrEmpty(verification_code)) {
//            showToast("请输入短信验证码");
            showConfirmAlert(mActivity, "请输入短信验证码");
            return false;
        }
        return true;
//        setResult(RESULT_OK);
//        finish();
    }

    boolean isTimeOver = true;

    /**
     * 发送短信验证码
     */
    private void sendSmsCode(String mobileNo) {
        if (mentorApplication.needLogin()) {
            ActivityUtils.gotoLogin(this, this.hasUser(), false, this.findUserId());
            return;
        }
        isGetVerificationCode = true;
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//replace 从登录对象身上获取-基金帐号
        params.put("token", "" + mentorApplication.userBean.getToken());//replace 从登录对象身上获取
        params.put("mobileNo", "" + mobileNo);

        Logger.t("-----SEND_SMS_CODE-----").d(HttpUtils.createRequestUrl(this, HostConstant.SEND_SMS_CODE, params));
        setVerificationCodeStatuts(false);
        OkGo.<String>post(HostConstant.SEND_SMS_CODE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        setVerificationCodeStatuts(true);
                        MentorLogger.LogJson(TAG, response.body());
                        parseJson_sms(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        sMobileNo = "";
                        isGetVerificationCode = false;
                        setVerificationCodeStatuts(true);
                        showToast(MentorConst.INTERNET_ERROR);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析接口返回的数据
     *
     * @param response
     */
    private void parseJson_sms(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            isGetVerificationCode = false;
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            isGetVerificationCode = false;
            return;
        }
        time.start();
        isGetVerificationCode = true;
        sMobileNo = et_mobile_val.getText().toString();
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            isTimeOver = false;
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);
            btn_get_verification_code.setText(millisUntilFinished / 1000 + "秒后重发");
        }

        @Override
        public void onFinish() {
            isTimeOver = true;
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setClickable(true);
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
            if (!Pattern.matches(MentorConst.REGEX_MOBILE, et_mobile_val.getText().toString())) {
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                btn_get_verification_code.setClickable(false);
            }
        }
    }

    public void save() {
        if (!checkData()) {
            return;
        }

        if (mentorApplication.needLogin()) {
            ActivityUtils.gotoLogin(this, this.hasUser(), false, this.findUserId());
            return;
        }
        String mobile = et_mobile_val.getText().toString();
        String verification_code = et_verification_code_val.getText().toString();
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("newMobileNo", mobile);// 新手机号
        params.put("verifyCode", verification_code);// 短信验证码
        OkGo.<String>post(HostConstant.CHANGE_MOBILE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "修改手机号成功", response.body());
                        updateMobile(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateMobile(String response) {
        BaseBean bean;

        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception e) {
            showConfirmAlert(this, "提示", "数据解析错误");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
        Intent intent = new Intent();
        String mobile = et_mobile_val.getText().toString();
        intent.putExtra("mobile", mobile);
        mentorApplication.accountLoginBean.getData().setMobileNo(mobile);
        showSuccessAlert(intent);
    }

    private void showSuccessAlert(final Intent intent) {
        IcbcDialog showConfirmAlertDialog = new IcbcDialog(this);
        showConfirmAlertDialog = new IcbcDialog(this);
        showConfirmAlertDialog.setCancelable(false);
        showConfirmAlertDialog.setAnimationEnable(true);
        showConfirmAlertDialog.setTitle("提示");
        showConfirmAlertDialog.setmPositiveBackgroundResId(R.drawable.sel_def_gray_pos);
        showConfirmAlertDialog.setContentText("手机号修改成功");
        showConfirmAlertDialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                setResult(RESULT_OK, intent);
                finish();
            }
        }).show();
    }

    private void setVerificationCodeStatuts(boolean isOpen) {
        if (isOpen) {
            if (et_mobile_val.getText().toString().length() < 11) {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                btn_get_verification_code.setClickable(false);
            } else {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
                btn_get_verification_code.setClickable(true);
            }

        } else {
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);

        }
    }
}
